package pixivPc.ui;

import java.awt.FlowLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.HashMap;
import java.util.Map;

import javax.swing.JFrame;

import pixivPc.task.BaseTask;

/**
 * 主界面
 * 
 * @author wangm
 *
 */
public class MainFrame extends JFrame {

	public Map<String, Panel> panelMap;

	public MainFrame() {
		panelMap = new HashMap<>();
		this.setLayout(new FlowLayout());
		// size
		this.setSize(800, 600);
		this.setVisible(true);
		// 退出事件
		this.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});

	}

	/**
	 * 获取或新建界面
	 * 
	 * @param name
	 *            界面名
	 * @return
	 */
	public Panel getPanel(String name) {
		if (panelMap.containsKey(name)) {
			return panelMap.get(name);
		}
		Panel p = new Panel(name);
		panelMap.put(name, p);
		this.add(p);
		return p;
	}

	/**
	 * 删除界面
	 * 
	 * @param name
	 *            界面名
	 * @return
	 */
	public void deletePanel(String name) {
		Panel panel = getPanel(name);
		this.remove(panel);
		panelMap.remove(name);
	}

	/**
	 * 执行task
	 * 
	 * @param name
	 *            界面名
	 * @param task
	 */
	public void runTask(String name, BaseTask task) {
		task.run(getPanel(name));
		this.pack();
	}

	/**
	 * 执行task
	 * 
	 * @param panel
	 *            界面
	 * @param task
	 */
	public void runTask(Panel panel, BaseTask task) {
		task.run(panel);
		this.pack();
	}

	/**
	 * 新建界面并执行task
	 * 
	 * @param name
	 *            界面名
	 * @param task
	 */
	public void runTaskWithNewPanel(String name, BaseTask task) {
		deletePanel(name);
		runTask(name, task);
	}

}
